package org.jeecg.modules.yfFenfgl.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.repository.Model;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.JsonUtils;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.yfFenfgl.entity.HqYfFenfgl;
import org.jeecg.modules.yfFenfgl.mapper.HqYfFenfglMapper;
import org.jeecg.modules.yfFenfgl.service.IHqYfFenfglService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 分房管理
 * @Author: jeecg-boot
 * @Date:   2020-07-15
 * @Version: V1.0
 */
@Service
public class HqYfFenfglServiceImpl extends ServiceImpl<HqYfFenfglMapper, HqYfFenfgl> implements IHqYfFenfglService {

    @Autowired
    private IdentityService identityservice;
    @Autowired
    private RuntimeService runtimeservice;
    @Autowired
    private TaskService taskService;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private HqYfFenfglMapper hqYfFenfglMapper;




    @Override
    public IPage<HqYfFenfgl> myApplyList(Page<HqYfFenfgl> page, LoginUser user, HqYfFenfgl hqYfFenfgl) {
        return this.baseMapper.myApplyList(page,user,hqYfFenfgl);
    }



    @Override
    public IPage<HqYfFenfgl> myTodoTasks(Page<HqYfFenfgl> page, LoginUser user, HqYfFenfgl hqYfFenfgl) {
        return this.baseMapper.myTodoTasks(page,user,hqYfFenfgl);
    }

    @Override
    public IPage<HqYfFenfgl> myDoneTasks(Page<HqYfFenfgl> page, LoginUser user, HqYfFenfgl hqYfFenfgl) {
        return this.baseMapper.myDoneTasks(page,user,hqYfFenfgl);
    }

    @Override
    public void startFlow(HqYfFenfgl hqYfFenfgl, LoginUser loginUser) {
        String spr = "shenpiren";
        String zg = "政治工作处";
        String jj = "纪检监察处";
        String orgCode = loginUser.getOrgCode();
        int length = orgCode.length();
        List<SysUser> selectzg = null;
        List<SysUser> selectjj = null;
        List<SysUser> shenpiren = sysUserService.queryByPost(orgCode,spr);
        if(CollectionUtils.isEmpty(shenpiren)) {
            throw new RuntimeException("当前部门审批人为空");
        }
        String businesskey = "" + hqYfFenfgl.getId();
        identityservice.setAuthenticatedUserId(loginUser.getUsername());
//      部门字符的长度
        if (length>=6) {
             orgCode = orgCode.substring(0, 6);
        }
        boolean iswuXueYuan = isWuXueYuan(orgCode);
//        给政治工作处赋值
        if (iswuXueYuan){
             selectzg = sysUserService.selectspr(orgCode, spr, zg);
             selectjj = sysUserService.selectspr("A01", spr, jj);
             if (CollectionUtils.isEmpty(selectzg)){
                 throw  new RuntimeException("当前部门没有政工处审批人");
             }if (CollectionUtils.isEmpty(selectjj)){
                 throw new RuntimeException("当前部门没有纪检处审批人");
            }
        }else {
            selectzg = sysUserService.selectspr("A01",spr,zg);
            selectjj = sysUserService.selectspr("A01",spr,jj);
            if (CollectionUtils.isEmpty(selectzg)){
                throw  new RuntimeException("当前部门没有政工处审批人");
            }if (CollectionUtils.isEmpty(selectjj)){
                throw new RuntimeException("当前部门没有纪检处审批人");
            }
        }

        Map<String, Object> variables = new HashMap<String, Object>();
//        申请用户
        variables.put("applyUser", loginUser.getUsername());
//        单位审计
        variables.put("auditUser",shenpiren.get(0).getUsername());
//        政工
        variables.put("zhengg",selectzg.get(0).getUsername());
//        纪检
        variables.put("jij",selectjj.get(0).getUsername());
//        判断是否五个学院
        variables.put("isWxy",iswuXueYuan);


        Model modelData = repositoryService.getModel("665001");
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(modelData.getDeploymentId()).singleResult();
        ProcessInstance instance = runtimeservice.startProcessInstanceById(processDefinition.getId(),businesskey,variables);
        String instanceid=instance.getId();
        hqYfFenfgl.setProcessInstanceId(instanceid);
        Task task = taskService.createTaskQuery().processInstanceId(instance.getId()).taskAssignee(loginUser.getUsername()).singleResult();
        hqYfFenfgl.setTaskId(task.getId());
//        设置流程刚开始审核状态
        hqYfFenfgl.setProcessStatus(0);
        hqYfFenfgl.setCreateTime(new Date());
        this.baseMapper.updateById(hqYfFenfgl);
        taskService.complete(task.getId(),variables);
    }

    @Override
    public void complateTask(LoginUser loginUser, String taskId,String processInstanceId, Integer status, String memo ,String fuj) {
        if(StringUtils.isBlank(memo)){
            memo = status == 1?"通过":"驳回";
        }
        Map map = new HashMap(){{
            put("status",status);
        }};
        map.put("memo",memo);
        taskService.addComment(taskId,processInstanceId, JsonUtils.toJsonString(map));
        taskService.complete(taskId,map);
        System.out.println("开始审核！！！！");
//        审核过程赋值
        HqYfFenfgl oneHqYfFenfgl = hqYfFenfglMapper.selectByprocessInstanceID(processInstanceId);
        Integer processStatus = oneHqYfFenfgl.getProcessStatus();
        Date endTime = oneHqYfFenfgl.getEndTime();

            oneHqYfFenfgl.setFuj(fuj);
            updateById(oneHqYfFenfgl);
//        System.out.println("status:::::::::::::::::::::::::::::::::" + status);
            if (status == 1 && null == endTime &&  !processStatus.equals(1) ) {
                oneHqYfFenfgl.setProcessStatus(1);
                updateById(oneHqYfFenfgl);

            } else if ( status == 0 && null == endTime && !processStatus.equals(3)) {
                oneHqYfFenfgl.setProcessStatus(3);
                updateById(oneHqYfFenfgl);
            } else if (null != endTime){
                oneHqYfFenfgl.setProcessStatus(2);
                updateById(oneHqYfFenfgl);
            }

    }

    @Override
    public void applyAgain(HqYfFenfgl hqYfFenfgl, LoginUser user) {
        Task task = taskService.createTaskQuery().processInstanceId(hqYfFenfgl.getProcessInstanceId()).taskAssignee(user.getUsername()).singleResult();
        hqYfFenfgl.setTaskId(task.getId());
//        重提之后将状态码设置成0代表未开始
        hqYfFenfgl.setProcessStatus(0);
        this.baseMapper.updateById(hqYfFenfgl);
        Map<String, Object> variables = new HashMap<String, Object>();
        variables.put("status",null);
        taskService.complete(task.getId(),variables);
    }

    @Override
    public IPage<HqYfFenfgl> guidan(Page<HqYfFenfgl> page, HqYfFenfgl hqYfFenfgl) {
        return baseMapper.guidan(page,hqYfFenfgl);
    }

    @Override
    public List<HqYfFenfgl> guidanExcel(HqYfFenfgl hqYfFenfgl) {
        return baseMapper.guidanExcel(hqYfFenfgl);
    }

    //  判断是否为五个学院单位{通信工程学院、指挥控制学院、野战工程学院、国防工程学院、研究生院}
    public static boolean isWuXueYuan(String orgCode){
        return orgCode.equals("A01A14")||orgCode.equals("A01A15")||orgCode.equals("A01A16")
                ||orgCode.equals("A01A17")||orgCode.equals("A01A18");
    }

}
